// 宿舍楼管理相关功能
const BuildingManager = {
    // 加载宿舍楼列表
    async loadBuildings() {
        loading.show();
        try {
            Debug.log('开始加载宿舍楼列表');
            const buildings = await API.buildings.getAll();
            
            if (!buildings || buildings.length === 0) {
                document.getElementById('buildingList').innerHTML = `
                    <div class="empty-state">
                        <p>暂无宿舍楼数据</p>
                        <button class="primary-btn" onclick="BuildingManager.showAddForm()">
                            <i class="icon add-icon"></i>添加宿舍楼
                        </button>
                    </div>
                `;
                return;
            }

            const buildingList = document.getElementById('buildingList');
            buildingList.innerHTML = buildings.map(building => `
                <div class="card">
                    <h3>${building.buildingName}</h3>
                    <p>楼层数：${building.floors}</p>
                    <p>描述：${building.description || '无'}</p>
                    <p class="text-muted">创建时间：${new Date(building.createdAt).toLocaleString()}</p>
                    <div class="card-actions">
                        <button class="primary-btn" onclick="BuildingManager.edit(${building.id})">
                            <i class="icon edit-icon"></i>编辑
                        </button>
                        <button class="danger-btn" onclick="BuildingManager.delete(${building.id})">
                            <i class="icon delete-icon"></i>删除
                        </button>
                    </div>
                </div>
            `).join('');
            
            Debug.log('宿舍楼列表加载完成', buildings);
        } catch (error) {
            Debug.error('加载宿舍楼列表失败', error);
            document.getElementById('buildingList').innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                    <button onclick="BuildingManager.loadBuildings()">重试</button>
                </div>
            `;
        } finally {
            loading.hide();
        }
    },

    // 显示添加表单
    showAddForm() {
        document.getElementById('addBuildingForm').reset();
        showModal('addBuildingModal');
    },

    // 显��编辑表单
    async edit(id) {
        try {
            const building = await API.buildings.getById(id);
            const form = document.getElementById('editBuildingForm');
            
            form.elements['id'].value = building.id;
            form.elements['buildingName'].value = building.buildingName;
            form.elements['floors'].value = building.floors;
            form.elements['description'].value = building.description || '';
            
            showModal('editBuildingModal');
        } catch (error) {
            Debug.error('获取宿舍楼信息失败', error);
            alert('获取宿舍楼信息失败');
        }
    },

    // 删除宿舍楼
    async delete(id) {
        if (!confirm('确定要删除这栋宿舍楼吗？删除后将无法恢复，且会同时删除所有相关的房间和学生数据。')) {
            return;
        }
        
        try {
            loading.show();
            await API.buildings.delete(id);
            Debug.log('宿舍楼删除成功:', id);
            this.loadBuildings();
        } catch (error) {
            Debug.error('删除宿舍楼失败:', error);
            alert('删除宿舍楼失败: ' + (error.message || '未知错误'));
        } finally {
            loading.hide();
        }
    },

    // 初始化事件监听
    init() {
        // 添加表单提交处理
        document.getElementById('addBuildingForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const building = {
                buildingName: formData.get('buildingName'),
                floors: parseInt(formData.get('floors')),
                description: formData.get('description')
            };

            try {
                loading.show();
                await API.buildings.create(building);
                hideModal('addBuildingModal');
                this.loadBuildings();
                e.target.reset();
            } catch (error) {
                Debug.error('添加宿舍楼失败:', error);
                alert('添加宿舍楼失败: ' + error.message);
            } finally {
                loading.hide();
            }
        });

        // 编辑表单提交处理
        document.getElementById('editBuildingForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const building = {
                id: parseInt(formData.get('id')),
                buildingName: formData.get('buildingName'),
                floors: parseInt(formData.get('floors')),
                description: formData.get('description')
            };

            try {
                loading.show();
                await API.buildings.update(building.id, building);
                hideModal('editBuildingModal');
                this.loadBuildings();
                e.target.reset();
            } catch (error) {
                Debug.error('更新宿舍楼失败:', error);
                alert('更新宿舍楼失败: ' + error.message);
            } finally {
                loading.hide();
            }
        });
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    BuildingManager.init();
});

// 导出全局函数（如果需要）
window.showAddBuildingForm = () => BuildingManager.showAddForm(); 